package com.neusoft.hifly.commons.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.hifly.commons.exception.SystemErrorException;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

/**
 * Title: 核心类库
 * <p>
 * Description: Excel工具类
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
public class EasyPoiUtil {
	/**
	 * 导出Excel文件
	 * 
	 * @param savePath
	 *            文件路径
	 * @param title
	 *            标题
	 * @param sheetName
	 *            Sheet页标题
	 * @param pojoClass
	 *            映射的实体类
	 * @param dataSet
	 *            数据集合
	 */
	public static void writeExcel(final String savePath, String title, String sheetName, Class<?> pojoClass,
			Collection<?> dataSet) {
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, dataSet);
		workbook.getSheetAt(0).setDefaultRowHeight((short) 21);

		try {

			File localFile = new File(savePath);
			OutputStream os = new FileOutputStream(localFile);

			workbook.write(os);
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 功能描述：复杂导出Excel，包括文件名以及表名。创建表头
	 *
	 * @param list
	 *            导出的实体类
	 * @param title
	 *            表头名称
	 * @param sheetName
	 *            sheet表名
	 * @param pojoClass
	 *            映射的实体类
	 * @param isCreateHeader
	 *            是否创建表头
	 * @param fileName
	 *            文件名
	 * @param response
	 *            返回
	 */
	public static void exportExcel(final List<?> list, final String title, final String sheetName,
			final Class<?> pojoClass, final String fileName, final boolean isCreateHeader,
			final HttpServletResponse response) {
		final ExportParams exportParams = new ExportParams(title, sheetName);
		exportParams.setCreateHeadRows(isCreateHeader);
		EasyPoiUtil.defaultExport(list, pojoClass, fileName, response, exportParams);
	}

	/**
	 * 功能描述：复杂导出Excel，包括文件名以及表名,不创建表头
	 *
	 * @param list
	 *            导出的实体类
	 * @param title
	 *            表头名称
	 * @param sheetName
	 *            sheet表名
	 * @param pojoClass
	 *            映射的实体类
	 * @param fileName
	 *            文件名
	 * @param response
	 *            返回
	 */
	public static void exportExcel(final List<?> list, final String title, final String sheetName,
			final Class<?> pojoClass, final String fileName, final HttpServletResponse response) {
		EasyPoiUtil.defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
	}

	/**
	 * 功能描述：Map 集合导出
	 *
	 * @param list
	 *            实体集合
	 * @param fileName
	 *            导出的文件名称
	 * @param response
	 *            返回
	 */
	public static void exportExcel(final List<Map<String, Object>> list, final String fileName,
			final HttpServletResponse response) {
		EasyPoiUtil.defaultExport(list, fileName, response);
	}

	/**
	 * 功能描述：默认导出方法
	 *
	 * @param list
	 *            导出的实体集合
	 * @param fileName
	 *            导出的文件名
	 * @param pojoClass
	 *            pojo实体
	 * @param exportParams
	 *            ExportParams封装实体
	 * @param response
	 *            返回
	 */
	private static void defaultExport(final List<?> list, final Class<?> pojoClass, final String fileName,
			final HttpServletResponse response, final ExportParams exportParams) {
		final Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
		if (workbook != null) {
			EasyPoiUtil.downLoadExcel(fileName, response, workbook);
		}
	}

	/**
	 * 功能描述：Excel导出
	 *
	 * @param fileName
	 *            文件名称
	 * @param response
	 *            返回
	 * @param workbook
	 *            Excel对象
	 */
	private static void downLoadExcel(final String fileName, final HttpServletResponse response,
			final Workbook workbook) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
			workbook.write(response.getOutputStream());
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 功能描述：默认导出方法
	 *
	 * @param list
	 *            导出的实体集合
	 * @param fileName
	 *            导出的文件名
	 * @param response
	 */
	private static void defaultExport(final List<Map<String, Object>> list, final String fileName,
			final HttpServletResponse response) {
		final Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
		if (workbook != null) {
			EasyPoiUtil.downLoadExcel(fileName, response, workbook);
		}
	}

	/**
	 * 功能描述：根据文件路径来导入Excel
	 *
	 * @param filePath
	 *            文件路径
	 * @param pojoClass
	 *            Excel实体类
	 * @return list
	 */
	public static <T> List<T> importExcel(final String filePath, final Class<T> pojoClass) {
		return importExcel(filePath, 0, 0, pojoClass);
	}

	/**
	 * 功能描述：根据文件路径来导入Excel
	 *
	 * @param filePath
	 *            文件路径
	 * @param titleRows
	 *            表标题的行数
	 * @param headerRows
	 *            表头行数
	 * @param pojoClass
	 *            Excel实体类
	 * @return list
	 */
	public static <T> List<T> importExcel(final String filePath, final int titleRows, final int headerRows,
			final Class<T> pojoClass) {
		// 判断文件是否存在
		if (StringUtils.isBlank(filePath)) {
			return null;
		}
		final ImportParams params = new ImportParams();
		if (titleRows > 0) {
			// 表格标题行数,默认0，意思就是告诉系统你的标题栏是在第几行，一般标题栏都在首行，默认是0
			params.setTitleRows(titleRows);
		}
		if (headerRows > 0) {
			// 表头行数,默认1
			params.setHeadRows(headerRows);
		}
		List<T> list = null;
		try {
			list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
		} catch (final NoSuchElementException e) {
			throw new RuntimeException("模板不能为空");
		} catch (final Exception e) {
			e.printStackTrace();

		}
		return list;
	}

	/**
	 * 功能描述：根据接收的Excel文件来导入Excel,并封装成实体类
	 *
	 * @param file
	 *            上传的文件
	 * @param pojoClass
	 *            Excel实体类
	 * @return list
	 */
	public static <T> List<T> importExcel(final MultipartFile file, final Class<T> pojoClass)
			throws SystemErrorException {
		return importExcel(file, 0, 0, pojoClass);
	}

	/**
	 * 功能描述：根据接收的Excel文件来导入Excel,并封装成实体类
	 *
	 * @param file
	 *            上传的文件
	 * @param titleRows
	 *            表标题的行数
	 * @param headerRows
	 *            表头行数
	 * @param pojoClass
	 *            Excel实体类
	 * @return list
	 */
	public static <T> List<T> importExcel(final MultipartFile file, final int titleRows, final int headerRows,
			final Class<T> pojoClass) throws SystemErrorException {
		if (file == null) {
			return null;
		}
		final ImportParams params = new ImportParams();
		if (titleRows > 0) {
			params.setTitleRows(titleRows);
		}
		if (headerRows > 0) {
			params.setHeadRows(headerRows);
		}
		List<T> list = null;
		try {
			list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
		} catch (final NoSuchElementException e) {
			throw new SystemErrorException("excel文件不能为空");
		} catch (final Exception e) {
			throw new SystemErrorException(e.getMessage());

		}
		return list;
	}

}